#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextEdit>
#include <QFileDialog>
#include <QDebug>
#include <fstream>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("我的word文件");

    QMenuBar* mb = new QMenuBar(this);
    this->setMenuBar(mb);

    QMenu* m = new QMenu("文件");
    mb->addMenu(m);

    QAction* a1 = new QAction("打开");
    QAction* a2 = new QAction("保存");
    QAction* a3 = new QAction("关闭");

    m->addAction(a1);
    m->addAction(a2);
    m->addAction(a3);

    te = new QTextEdit(this);
    this->setCentralWidget(te);
    te->setPlaceholderText("请输入");

    connect(a1,&QAction::triggered,this,&MainWindow::load);
    connect(a2,&QAction::triggered,this,&MainWindow::save);
    connect(a3,&QAction::triggered,this,&MainWindow::quit);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::save()
{
    QFileDialog* dg = new QFileDialog(this);
    QString filename = dg->getSaveFileName(this,"保存文件","C:/Users/14725/Desktop");
    qDebug() << filename;
    std::ofstream file(filename.toStdString().c_str());
    if(!file.is_open())
    {
        qDebug() << "文件保存失败";
        return;
    }
    const QString& text = te->toPlainText();
    file<<text.toStdString();
    file.close();
}

void MainWindow::load()
{
    QFileDialog* d = new QFileDialog(this);
    QString filename = d->getOpenFileName(this,"加载文件","C:/Users/14725/Desktop");
    std::ifstream file(filename.toStdString().c_str());
    if(!file.is_open())
    {
        qDebug() << "文件加载失败";
        return;
    }
    std::string content;
    std::string line;
    while (std::getline(file, line))
    {
        content += line;
        content += "\n";
    }
    file.close();
    QString text = QString::fromStdString(content);
    te->setPlainText(text);

}

void MainWindow::quit()
{
    this->close();
}

